package com.fdd.spring.fddapplicationtext;
import com.fdd.spring.bean.Monster;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class FddApplicationContext {
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    public FddApplicationContext(String iocBeanXmlFile) throws Exception {
        String path = this.getClass().getResource("/").getPath();
        //通过dom4j解析xml文件
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(path + iocBeanXmlFile);
        //解析xml文件
        Element rootElement = document.getRootElement();

        Element bean =(Element) rootElement.elements().get(0);
        //获取相关属性id和class
        String id = bean.attributeValue("id");
        String classFullPath = bean.attributeValue("class");
        System.out.println(id);
        System.out.println(classFullPath);
        //获取对象的属性
        List<Element> propertyList = bean.elements("property");
        Integer monsterid = Integer.parseInt(propertyList.get(0).attributeValue("value"));
        String name = propertyList.get(1).attributeValue("value");
        String skill = propertyList.get(2).attributeValue("value");

        Class<?> aClass = Class.forName(classFullPath);
        Monster monster = (Monster)aClass.newInstance();
        monster.setId(monsterid);
        monster.setName(name);
        monster.setSkill(skill);

        singletonObjects.put(id,monster);

    }

    public Object getBean(String beanId) {
        return singletonObjects.get(beanId);
    }
}
